# desktop_app/controllers/api_client.py
import requests
from typing import Optional, Dict, Any
import logging
import os
from dotenv import load_dotenv
from pathlib import Path

logging.basicConfig(level=logging.INFO)

class ApiClient:
    def __init__(self):

        # 加载.env文件（从项目根目录）
        env_path = Path(__file__).parent.parent.parent / '.env'
        load_dotenv(env_path)
        
        # 获取配置（环境变量优先，不存在则使用默认值）
        self.base_url = os.getenv('API_BASE_URL', 'http://localhost:5000')


        #self.base_url = base_url.rstrip('/')  # 移除末尾可能存在的斜杠


    def get_video_types(self):
        """获取视频类型列表 ← 新增方法"""
        try:
            response = requests.get(f"{self.base_url}/api/video_types")
            if response.status_code == 200:
                return response.json().get('data', [])
            return []
        except requests.exceptions.RequestException:
            return []
    
    def fetch_video_data(
        self, 
        video_url: str, 
        video_type: Optional[int] = None
    ) -> Dict[str, Any]:
        """从API获取视频分析数据
        
        Args:
            video_url: 视频URL地址
            video_type: 可选视频类型ID
            
        Returns:
            包含分析结果或错误的字典
        """
        endpoint = f"{self.base_url}/api/data"
        payload = {
            "video_url": video_url,
            "video_type": video_type
        }
        
        try:
            response = requests.post(
                url=endpoint,
                json=payload,
                timeout=10,
                headers={"Content-Type": "application/json"}
            )
            response.raise_for_status()  # 自动处理4xx/5xx错误
            return response.json()
            
        except requests.exceptions.Timeout:
            logging.warning("API请求超时")
            return {"error": "请求超时", "code": 408}
            
        except requests.exceptions.RequestException as e:
            logging.error(f"网络错误: {str(e)}")
            return {
                "error": "网络连接失败",
                "details": str(e),
                "code": 500
            }
            
        except ValueError as e:  # JSON解析错误
            logging.error(f"响应解析失败: {str(e)}")
            return {
                "error": "无效的API响应",
                "details": str(e),
                "code": 502
            }